package com.leo.ktvplayer.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.leo.ktvplayer.base.App;

/**
 *
 */
public class BleManager {
    private static BleManager manager;

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;

    public static BleManager getInstance(){
        if (manager == null) {
            manager = new BleManager();
        }
        return manager;
    }

    /**
     * Connect to GattService.
     * @param macAddress
     */
    public void connect(String macAddress){
        BluetoothDevice device = null;
        if (macAddress != null) {
            device = mBluetoothAdapter.getRemoteDevice(macAddress);
        }

        mBluetoothGatt = device.connectGatt(App.getInstance(),false,callback);
    }

    /**
     * disconnect
     */
    public void disconnect(){
        if (mBluetoothGatt != null){
            mBluetoothGatt.disconnect();
        }
    }

    /**
     * initialize all service
     */
    public void initialize(){
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) App.getInstance().getSystemService(Context.BLUETOOTH_SERVICE);
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();

    }

    public void setGattBluetoothGattCharacteristic(BluetoothGattCharacteristic characteristic){
        if (characteristic != null && mBluetoothGatt != null) {
            mBluetoothGatt.setCharacteristicNotification(characteristic,true);
        }
    }

    public BluetoothGatt getClient(){
        return mBluetoothGatt;
    }

    private BluetoothGattCallback callback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
        }
    };
}
